import vjmap3d, { App, PathTubeEntities } from "vjmap3d";
import * as THREE from "three"
export const loadDataScene = async (app: App, dataId: string) => {
    let outMaterial = new THREE.MeshPhongMaterial({
        color: 0x7dffeb,
        side: THREE.FrontSide
    });
  
    let innerMaterial = new THREE.MeshPhongMaterial({
        color: 0x7dffeb,
        side: THREE.FrontSide
    });
    
    let nodeOutMaterial = new THREE.MeshPhongMaterial({
        color: 0x7dffeb,
        side: THREE.FrontSide
    });
    
    let results = await app.svc.getCustomData(dataId);
    if (!results.status) {
        app.logInfo("没有找到数据项的值：" + dataId, "error")
        return;
    }
    results = results.data;

    //let box3d = new THREE.Box3();
    let allPts = []
    
    let lineDatas = []
    let tubeDatas = [];
    if (results && results.length > 0) {
        for(let n = 0; n < results.length; n++) {
            let linePoints =  results[n].paths;
          
            // @ts-ignore
            //linePoints = linePoints.map(p => vjmap3d.toVector3([p[0], p[2], p[1]]));
            linePoints = linePoints.map(p => vjmap3d.toWorld([p[0], p[1], p[2]]));
            
            lineDatas.push(linePoints)
    
             // 记录下所有点坐标，用来计算范围
            allPts.push(...linePoints)
    
            tubeDatas.push({
                paths: linePoints,
                name:  results[n].name + ''
            })
        }
    }
    
    
    // 获取数据范围
    // box3d.setFromPoints(allPts)
    
    // // 计算中心点
    // let center = box3d.min.clone().add(box3d.max).multiplyScalar(0.5);
    
    // // 因为业务数据有可能坐标很大或很小，所以对整个应用根据坐标范围对坐标进行一个平移和缩放
    // app.centerOrigin = new THREE.Vector3(center.x, box3d.min.y, center.z);
    // // 根据最大距离，缩放至宽度为200左右
    // let dist = Math.max(box3d.max.x - box3d.min.x, box3d.max.z - box3d.min.z);
    // app.scaleOrigin = 500 / dist;
    
    // // 根据设置的平移和缩放量，重新计算下坐标
    // for(let p of tubeDatas ) {
    //     p.paths = p.paths.map((t: any) => vjmap3d.toWorld(t.toArray()).toArray())
    // }
    
    let tubeEntity: PathTubeEntities;
    let cancelActionCb: any;
    const createTubeEntity = (data: any, sect?: any) => {
        if (tubeEntity) {
            // 如果之前实体创建了，先删除
            tubeEntity.entity.remove();
            //@ts-ignore
            tubeEntity = null;
        }
        if (cancelActionCb) {
            // 如果之前设置了纹理流动,先取消了
            cancelActionCb()
            cancelActionCb = null;
        }
        let opts = {
            data: data,
           
            nodeRadius: 0.025,
            innerSideMaterial: innerMaterial,
            outerMaterial: outMaterial,
            nodeOuterMaterial: nodeOutMaterial,
            sect: sect ?? {
                shape: "arch",
                rectWidth: 0.05,
                rectHeight: 0.025
            },
            /** 建立拓扑关系策略（默认nodeIntersect） nodeIntersect 一条管道的始末节点与另一条相交时，自动把另一条拆成多段建立拓扑。nodeEqual 一条管道的始末节点与另一条管道的始末节点相等时建立拓扑，不会自动拆分 */
            topoStrategy: "nodeIntersect"
        }
        // @ts-ignore
        let pathTube = new vjmap3d.PathTubeEntities(opts);
        pathTube.addTo(app);
        // 
        for(let n = 0; n < pathTube.entity.childrens.length; n++) {
            let ent = pathTube.entity.childrens[n];
            let text = ent.node.isNode ? 
            `节点：关联${ent.node.userData.dataIndexs} 条路径`:
            pathTube.data[ent.node.userData.dataIndex].name
            ent.add(vjmap3d.EventModule, {
                clickHighlight: true,
                highlightOpacity: 0.2,
                hoverSelect: true,
                // @ts-ignore
                hoverHtmlText: `<span style="color:#00f">${text}</span>`,
                popupOptions: {
                    anchor: "bottom"
                }
            });
        }
    
        tubeEntity = pathTube;
    }
    
    createTubeEntity(tubeDatas)

    return {
        tubeDatas
    }
}
